#include "ztcpserver.h"



ZTcpServer::ZTcpServer(QObject *parent):QTcpServer(parent)
{
    this->listen(QHostAddress::LocalHost,12345);
    connect(this,SIGNAL(newConnection()),this,SLOT(slotNewConnection()));
}

void ZTcpServer::push_back(QTcpSocket *tcpSocket)
{
    mListPTcpSocket.push_back(tcpSocket);
}

void ZTcpServer::removeOne(QTcpSocket *tcpSocket)
{
    mListPTcpSocket.removeOne(tcpSocket);
}

const QList<QTcpSocket *> &ZTcpServer::listPTcpSocket() const
{
    return mListPTcpSocket;
}

QStringList ZTcpServer::connectTcpSocketInfos()
{
    QStringList list;
    foreach (auto var, mListPTcpSocket) {
        list<<currentTcpSocketInfo(var);
    }
    return list;
}

QString ZTcpServer::currentTcpSocketInfo(QTcpSocket *tcpSocket)
{
    return "name:"+tcpSocket->peerName()+
            "address:"+tcpSocket->peerAddress().toString()+
            "port:"+QString::number(tcpSocket->peerPort());
}

void ZTcpServer::sendOtherTcpSocket(QTcpSocket *currentTcpSocket, ZTcpData data)
{
    QMutexLocker mutexLocker(&m_Mutex);
    foreach(auto var,mListPTcpSocket)
    {
        if(currentTcpSocket!=var)
        {
            qDebug()<<var;
            QDataStream out(var);
            out << data;
        }
    }
}





void ZTcpServer::slotNewConnection()
{
    QTcpSocket *tcpSocket = this->nextPendingConnection();
    connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisConnected()));
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(slotReadyRead()));
    mListPTcpSocket.append(tcpSocket);
    qDebug()<<"当前连接信息"<<connectTcpSocketInfos();
}

void ZTcpServer::slotDisConnected()
{
    QObject *object = this->sender();
    QTcpSocket *tcpSocket = static_cast< QTcpSocket *>(object);
    mListPTcpSocket.removeOne(tcpSocket);
    tcpSocket->disconnectFromHost();
    qDebug()<<"当前连接信息"<<connectTcpSocketInfos();
}

void ZTcpServer::slotReadyRead()
{
    QObject *object = this->sender();
    QTcpSocket *tcpSocket = static_cast< QTcpSocket *>(object);

    QDataStream in(tcpSocket);

    in >> m_TcpData;

    qDebug()<<m_TcpData;

    sendOtherTcpSocket(tcpSocket,m_TcpData);
}
